/*
 * timer.c
 *
 *  Created on: 2010-03-03
 *      Author: sikorskip
 */
#include <inttypes.h>
#include <avr/io.h>
#include "timer.h"
#include "spi/SPI.h"
#include "df/AT45DB011.h"
#include "rtc/DS1305.h"

void readTimer(struct timer *timer) {
	DATAFLASH_read_mem_page_to_buffer(0);
	while (!(DATAFLASH_read_mem_stat() & 0x80))
		;
	timer->minute = DATAFLASH_read_mem_buf(timer->id + 0x00);
	timer->hour = DATAFLASH_read_mem_buf(timer->id + 0x01);
	timer->allreadyTriggered = DATAFLASH_read_mem_buf(timer->id + 0x02);
	timer->active = DATAFLASH_read_mem_buf(timer->active + 0x03);
}

void writeTimer(struct timer *timer) {
	DATAFLASH_read_mem_page_to_buffer(0);
	while (!(DATAFLASH_read_mem_stat() & 0x80))
		;
	DATAFLASH_write_mem_buf(timer->id + 0x00, timer->minute);
	DATAFLASH_write_mem_buf(timer->id + 0x01, timer->hour);
	DATAFLASH_write_mem_buf(timer->id + 0x02, timer->allreadyTriggered);
	DATAFLASH_write_mem_buf(timer->id + 0x03, timer->active);
	DATAFLASH_write_mem_buffer_to_page(0);
	while (!(DATAFLASH_read_mem_stat() & 0x80))
		;
}

void checkTimer(struct timer *timer, uint8_t minutes, uint8_t hours) {
	if (timer->minute == minutes && timer->hour == hours && timer->active
			== MODE_ON) {
		if (timer->allreadyTriggered == 0) {
			timer->allreadyTriggered = 1;
			if (timer->mode == MODE_ON) {
				enablePowerOutput(timer->powerId);
			} else {
				disablePowerOutput(timer->powerId);
			}
			writeTimer(timer);
		}
	} else {
		timer->allreadyTriggered = 0;
		writeTimer(timer);
	}
}

void setupTimers() {
	DS1305_write_byte(0x8f, 0x01 | 0x02 | 0x04);

	int i = 0;
	for (i = 0; i < POWER_OUTPUT_COUNT * 2; i++) {
		readTimer(&powerTimers[i]);
	}
}

void checkTimers() {
	uint8_t hours = DS1305_read_byte(0x02);
	uint8_t minutes = DS1305_read_byte(0x01);

	int i = 0;
	for (i = 0; i < POWER_OUTPUT_COUNT * 2; i++) {
		checkTimer(&powerTimers[i], minutes, hours);
	}

}

uint8_t clockGetHour() {
	return DS1305_read_byte(0x02);
}

uint8_t clockGetMinute() {
	return DS1305_read_byte(0x01);
}

uint8_t clockGetSecond() {
	return DS1305_read_byte(0x00);
}
